import router from "./router";
import store from "./store";
import {
  Message
} from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import {
  getToken
} from "@/utils/auth";

NProgress.configure({
  showSpinner: false,
});

const whiteList = [
  "/login",
  "/oauthLogin",
  "/auth-redirect",
  "/bind",
  "/register",
  "/notAccessPer401",
  "/401",
  "/404",
  "/502",
  "/504",
  "/replacementTips",
  "/smartform/smartForm/list"
];

const reportPathPrefix = "/report";

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (!["/notAccessPer401", "/401", "/404", "/502", "/504"].includes(to.path)) {
    if (["/login", "/oauthLogin", "/index"].includes(to.path)) {
      //获取用户当前浏览器的类型信息,QQ浏览器进行拦截
      var explorer = navigator.userAgent;
      if (explorer.indexOf("QQBrowser") >= 0) {
        next({
          path: "/replacementTips",
        });
      }
    }
    if (getToken()) {
      /* has token*/
      if (to.path === "/login" || to.path === "/oauthLogin") {
        next({
          path: "/",
        });
        NProgress.done();
      } else {
        if (store.getters.roles.length === 0) {
          // 判断当前用户是否已拉取完user_info信息
          store
            .dispatch("GetInfo")
            .then((res) => {
              // 拉取user_info
              const roles = res.roles;
              // 拉取向导信息
              store.dispatch("loadCurrNotTriggerGuide");

              if (!roles.length && store.getters.permissions != "*:*:*") {
                store.dispatch("LogOut").then(() => {
                  next({
                    path: "/notAccessPer401",
                  });
                });
                return;
              }

              store
                .dispatch("GenerateRoutes", {
                  roles,
                })
                .then((accessRoutes) => {
                  // 根据roles权限生成可访问的路由表
                  router.addRoutes(accessRoutes); // 动态添加可访问路由表
                  router.addRoutes([{
                      path: "/smartform/hub/:pageCode",
                      component: (resolve) =>
                        require([
                          "@/views/smartform/smartForm/render",
                        ], resolve),
                      hidden: true,
                    },
                    {
                      path: "/smartform/view/:pageCode",
                      component: (resolve) =>
                        require([
                          "@/views/smartform/smartForm/viewRender",
                        ], resolve),
                      hidden: true,
                    },
                    {
                      path: "/smartform/workflow/:pageCode",
                      component: (resolve) =>
                        require([
                          "@/views/smartform/smartForm/workflow",
                        ], resolve),
                      hidden: true,
                    },
                  ]);
                  next({
                    ...to,
                    replace: true,
                  }); // hack方法 确保addRoutes已完成
                });
            })
            .catch((err) => {
              if (err && err.response && err.response.status == 502) {
                next({
                  path: "/502",
                });
              } else if (err && err.response && err.response.status == 502) {
                next({
                  path: "/504",
                });
              } else {
                store.dispatch("LogOut").then(() => {
                  Message.error(err);
                  next({
                    path: "/",
                  });
                });
              }
            });
        } else if (
          to.path.startsWith("/smartform/hub/") &&
          Object.keys(to.params).length === 0
        ) {
          next({
            ...to,
            params: {
              ...to.params,
              pageCode: to.path.substring(
                15,
                Math.max(to.path.indexOf("?"), to.path.length)
              ),
            },
          });
        } else if (
          to.path.startsWith("/smartform/view/") &&
          Object.keys(to.params).length === 0
        ) {
          next({
            ...to,
            params: {
              ...to.params,
              pageCode: to.path.substring(
                16,
                Math.max(to.path.indexOf("?"), to.path.length)
              ),
            },
          });
        } else if (
          to.path.startsWith("/smartform/workflow/") &&
          Object.keys(to.params).length === 0
        ) {
          next({
            ...to,
            params: {
              ...to.params,
              pageCode: to.path.substring(
                20,
                Math.max(to.path.indexOf("?"), to.path.length)
              ),
            },
          });
        } else {
          next();
        }
      }
    } else {
      // 没有token
      if (
        whiteList.indexOf(to.path) !== -1 ||
        to.path.startsWith(reportPathPrefix)
      ) {
        // 在免登录白名单，直接进入
        const enableSso =
          process.env.VUE_APP_ENABLE_SSO === true ||
          process.env.VUE_APP_ENABLE_SSO === "true";
        if (enableSso) {
          if (to.path === "/login") {
            localStorage.setItem("sso_redirect_uri", to.fullPath);
            next(`/oauthLogin`); // 否则全部重定向到单点登录页
          } else {
            next();
          }
        } else {
          if (to.path === "/oauthLogin") {
            next(`/login`);
          } else {
            next();
          }
        }
      } else {
        const enableSso =
          process.env.VUE_APP_ENABLE_SSO === true ||
          process.env.VUE_APP_ENABLE_SSO === "true";
        if (enableSso) {
          localStorage.setItem("sso_redirect_uri", to.fullPath);
          next(`/oauthLogin`); // 否则全部重定向到单点登录页
        } else {
          next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
        }
        NProgress.done();
      }
    }
  } else {
    next();
  }
});

router.afterEach(() => {
  NProgress.done();
});
